require 'thread'
require 'watir-webdriver'
require_relative 'request_page'

class ParallelRequestScraper

  def initialize(navigator, login_command, threads)
    @navigator = navigator
    @login_command = login_command
    @threads = threads
  end

  def scrape(request_ids, &block)
    @request_ids = request_ids.clone
    @semaphore = Mutex.new
    @threads.times.map { Thread.new { scrape_requests &block } }.each { |t| t.join }
  end

  private

  def scrape_requests
    b = Watir::Browser.new
    @login_command.execute b

    until @request_ids.empty?
      request = scrape_next_request b
      yield request if request
    end

    b.close
  end

  def scrape_next_request(b)
    id = next_request_id
    return unless id
    @navigator.goto "hd/ticket/euTicketView.ssp?ticket_id=#{id}&log=show", b
    request_page = RequestPage.new b
    request_page.get_request
  end

  def next_request_id
    @semaphore.synchronize { return @request_ids.pop }
  end

end